import React, { useEffect, useState } from "react";
import { ScrollView, Text, TextInput, View, StyleSheet } from "react-native";
import tw from "twrnc";
import Icon from "react-native-vector-icons/AntDesign";
import { router } from "expo-router";
import CountryFlag from "react-native-country-flag";
import { RadioButton, Modal } from "react-native-paper";
import TencentCaptcha from "@/components/TencentCaptcha";
import { post } from "@/utils/api";
import * as SecureStore from 'expo-secure-store';
import { NavigationProp, useNavigation } from '@react-navigation/native';

type RootStackParamList = {
  'mine': { id: string };
  // 其他路由的参数类型
};



export default function CodeLogin() {
  const navigation = useNavigation<NavigationProp<RootStackParamList>>();
  const goAreaCode = () => {
    // 跳转到选择区号页面
    router.push("/(auth)/area-code");
  };
  const [isChecked, setIsChecked] = useState(false);
  const handleCheckboxChange = () => {
    setIsChecked(!isChecked);
  };

  const [phoneNumber, setPhoneNumber] = useState("");
  const [isRequesting, setIsRequesting] = useState(false); // 控制请求状态，防止重复请求
  const [visible, setVisible] = React.useState(false);
  const [time, setTime] = useState(60);
  const [timer, setTimer] = useState(null);
  const [backendCode, setBackendCode] = useState("");
  const [frontendCode, setFrontendCode] = useState("");
  const showModal = () => {
    if (!phoneNumber) {
      alert("请输入手机号！");
      return;
    }

    if (time === 60) {
      setVisible(true);
    }
  };
  const hideModal = () => setVisible(false);
  const containerStyle = {
    backgroundColor: "white",
    padding: 10,
    height: 300,
    margin: 50,
    borderRadius: 10,
  };

  const handleCaptchaSuccess = () => {
    setVisible(false); // 关闭模态框
    startTimer(); // 开始倒计时
  };

  // 启动倒计时
  const startTimer = () => {
    setTime(60); // 每次重新获取验证码时重新初始化倒计时为60秒
    getCode();
    // 清除之前的定时器
    if (timer) {
      clearInterval(timer);
    }

    const newTimer = setInterval(() => {
      setTime((prevTime) => {
        if (prevTime <= 1) {
          clearInterval(newTimer); // 倒计时结束，清除定时器
          return 60; // 倒计时结束后重置为60秒
        }
        return prevTime - 1; // 每秒减一
      });
    }, 1000);

    setTimer(newTimer); // 保存定时器ID
  };

  const getCode = async () => {
    try {
      const res = await post('sendCode', { phoneNumber });
      if (res.vcode) {
        setBackendCode(String(res.vcode));
      } else {
        console.error('Invalid response format:', res);
      }
    } catch (error) {
      console.error('Request failed', error);
    }
  };

  const handleLogin = async () => {
    if (!isChecked) {
      alert('请先同意用户协议和隐私权政策');
      return;
    }
    if (phoneNumber === '') {
      alert("请输入手机号")
      return
    }

    // 检查手机号格式
    if (!/^\d{11}$/.test(phoneNumber)) {
      alert("请输入正确的手机号！");
      return;
    }
    if (frontendCode === '') {
      alert("请输入验证码")
      return
    }

    if (frontendCode === backendCode && backendCode) {
      const userList = await SecureStore.getItemAsync('userList');
      const userInfo = JSON.parse(userList || '[]').find(item => item.phoneNumber === phoneNumber);
      // 随机token
      const token = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);

      // 登录成功后保存token
      await SecureStore.setItemAsync('phoneNumber', phoneNumber)
      SecureStore.setItemAsync('token', token).then(() => {
        // navigation.navigate('mine', { id: userInfo.id });
        router.push('/(tabs)')
      })
    }
    else {
      alert("验证码错误！")
    }
  }

  useEffect(() => {
    return () => {
      if (timer) {
        clearInterval(timer); // 清理定时器
      }
    };
  }, [timer]); // 组件卸载时清除定时器

  return (
    <View style={tw`flex-1`}>
      <View style={tw`p-4`}>
        <Text style={tw`text-right text-slate-400`} onPress={() => { router.push('/(auth)/register') }}>注册账号</Text>
        <Text style={tw`text-lg font-bold mb-8`} >验证码登录</Text>
        <View style={tw`flex-row items-center border-2 border-gray-300 rounded-full my-1.5 px-2`}>
          <CountryFlag isoCode='CN' size={30} style={tw`rounded-full h-5 w-5 mx-3px`} />
          <Text>+86</Text>
          <View style={tw`mx-3px`}>
            <Icon
              name="caretdown"
              size={10}
              color="#4F8EF7"
              onPress={goAreaCode}
            />
          </View>
          <TextInput
            style={tw`p-2`}
            placeholder="请输入手机号"
            placeholderTextColor="#999999"
            value={phoneNumber}
            onChangeText={(text) => setPhoneNumber(text)}
          />
        </View>

        <View
          style={tw`flex-row items-center justify-between  border-2 border-gray-300 rounded-full my-1.5 px-2`}
        >
          <TextInput
            style={tw`p-2`}
            placeholder="请输入验证码"
            placeholderTextColor="#999999"
            value={frontendCode}
            onChangeText={(text) => setFrontendCode(text)}
          />
          <View>
            <Text style={tw`text-teal-300`} onPress={showModal}>
              {time === 60 ? "获取验证码" : `${time}s后重新获取`}
            </Text>
          </View>
        </View>

        <View style={tw`flex-row items-center justify-between my-1.5 px-5px`}>
          <Text onPress={() => router.push("/(auth)/pwd-login")}>密码登录</Text>
        </View>

        <View style={tw`flex-row items-center justify-center my-5`}>
          <View style={tw`flex items-center justify-center bg-gray-200 rounded-full w-16 h-16`}>
            <Icon name="arrowright" size={30} color="#A7ABAA" onPress={handleLogin} />
          </View>
        </View>
      </View>

      <View
        style={tw`flex-row items-center justify-center absolute bottom-2 left-0 right-0 mx-5`}
      >
        <RadioButton
          value={String(isChecked)}
          status={isChecked ? "checked" : "unchecked"}
          onPress={handleCheckboxChange}
          color="#26EBD7"
        />
        <Text style={tw`text-teal-300`}>《WorldTalks用户协议》</Text>
        <Text>和</Text>
        <Text style={tw`text-teal-300`}>《WorldTalks隐私权政策》</Text>
      </View>

      {/*验证码 */}

      <Modal
        visible={visible}
        onDismiss={hideModal}
        contentContainerStyle={containerStyle}
      >
        <View style={tw`flex-1 justify-center py-5`}>
          <TencentCaptcha onSuccess={handleCaptchaSuccess}></TencentCaptcha>
        </View>
      </Modal>
    </View>
  );
}
